import React from 'react';
import * as antdIcons from '@ant-design/icons';
import aliIconJson from '@/assets/ali-fonts/iconfont.json';
import './style.scss'

const aliNames = Array.from(aliIconJson.glyphs, item => item.font_class); //阿里图标的名称
aliNames.map((name, index) => aliNames[index] = `icon-${name}`);

enum Types {
    'ali',
    'antd',
}
interface PropsRule {
    name : string,
    type ?: keyof typeof Types,
    className ?: string
}

function Icon(props: PropsRule): React.ReactElement {
    const name = props.name;
    if (![...Object.keys(antdIcons), ...aliNames].includes(name)) {
        throw new Error('不存在此name图标');
    }
    const type = props.type || (name.indexOf('icon-') > -1 ? "ali" : "antd");
    switch (type) {
        case 'ali':
            return <i className={`iconfont ${name} aliIcon ${props.className}`}/>;
        case 'antd':
            const AntdIcon = antdIcons[name] as Function;
            return <AntdIcon className={props.className}/>;
    }
}

export default Icon;

const AntdIcon: React.FC<{ name: keyof typeof antdIcons }> = ({name}) => {
    const Icon = antdIcons[name] as React.FunctionComponent;
    return <Icon/>;
};

